package com.pinecone.controller;

import com.alibaba.fastjson.JSONObject;
import com.pinecone.common.exception.MinerException;
import com.pinecone.common.utils.HttpClientUtils;
import com.pinecone.common.utils.PageUtils;
import com.pinecone.common.utils.Query;
import com.pinecone.common.utils.R;
import com.pinecone.entity.*;
import com.pinecone.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hushangjie on 2017/10/1.
 */
@Controller
@RequestMapping("")
public class ViewController {
    @Autowired
    private LiveRoomService liveRoomService;
    @Autowired
    private LiveAdPageService liveAdPageService;
    @Autowired
    private LiveRoomTabService liveRoomTabService;
    @Autowired
    private LiveRoomCommentService liveRoomCommentService;
    @Autowired
    private LiveRecordService liveRecordService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private LiveRoomViewCodeService liveRoomViewCodeService;
    @RequestMapping("/view_code")
    public String CodeToView(@RequestParam(value = "room_id",required = true) String liveRoomId,Model model){
        model.addAttribute("liveRoomId",liveRoomId);
        return "view-code";
    }

    @RequestMapping("/live/{live_room_id}")
    public String liveRoom(@PathVariable(value = "live_room_id",required = true) String liveRoomId,
                           @ModelAttribute("access_token") String access_token,
                           @ModelAttribute("uid") String uid,
                           @ModelAttribute("user_type") String user_type,
                           @RequestParam(value="view_code",required = false,defaultValue = "0") int view_code,
                           HttpSession httpSession,
                           ModelMap model){
        LiveRoomEntity liveRoomEntity = liveRoomService.queryObject(liveRoomId);
        //判断直播间是否存在
        if (liveRoomEntity == null){
            throw new MinerException("直播间不存在");
        }
        //判断是否有引导页
        boolean isFromAdPage = httpSession.getAttribute("isFromAdPage")== null ? false:true;
        LiveAdPageEntity liveAdPageEntity = liveAdPageService.queryByLiveRoomId(liveRoomId);
        //无引导页
        if (liveAdPageEntity == null) {
            //判断房间是否有密码
            LiveRoomViewCodeEntity liveRoomViewCodeEntity = liveRoomViewCodeService.queryByRoomId(liveRoomId);
            boolean hasEnteredPwd = httpSession.getAttribute("viewCode") == null ? false : true;
            //需要观看码
            if (liveRoomViewCodeEntity != null && hasEnteredPwd == false){
                //观看码错误
                if (view_code == 0 || liveRoomViewCodeEntity.getViewCode() != view_code){
                    return "redirect:/view_code?room_id="+liveRoomId;
                }
                //观看码正确
                if (liveRoomViewCodeEntity.getViewCode() == view_code){
                    httpSession.setAttribute("viewCode",true);
                }
            }

            if (liveRoomEntity.getLiveStatus() == 2){
                //点播
                model.addAttribute("vodInfo", orgnaziRoomInfo(liveRoomEntity,uid,access_token,user_type));
                return "vod-player";
            }else {
                //直播或直播未开始
                model.addAttribute("liveInfo", orgnaziRoomInfo(liveRoomEntity,uid,access_token,user_type));
                return "live-player";
            }
        }
        //有引导页，已经访问过
        if (liveAdPageEntity != null && isFromAdPage == true){
            //判断房间是否有密码
            LiveRoomViewCodeEntity liveRoomViewCodeEntity = liveRoomViewCodeService.queryByRoomId(liveRoomId);
            boolean hasEnteredPwd = httpSession.getAttribute("viewCode") == null ? false : true;
            //需要观看码
            if (liveRoomViewCodeEntity != null && hasEnteredPwd == false){
                //观看码错误
                if (view_code == 0 || liveRoomViewCodeEntity.getViewCode() != view_code){
                    return "redirect:/view_code?room_id="+liveRoomId;
                }
                //观看码正确
                if (liveRoomViewCodeEntity.getViewCode() == view_code){
                    httpSession.setAttribute("viewCode",true);
                }
            }
            //已经从广告页面进来
            //httpSession.removeAttribute("isFromAdPage");
            if (liveRoomEntity.getLiveStatus() == 2){
                //点播
                model.addAttribute("vodInfo", orgnaziRoomInfo(liveRoomEntity,uid,access_token,user_type));
                return "vod-player";
            }else {
                //直播或直播未开始
                model.addAttribute("liveInfo", orgnaziRoomInfo(liveRoomEntity,uid,access_token,user_type));
                return "live-player";
            }
        }
        //有引导页但未访问过
        if (liveAdPageEntity != null && isFromAdPage == false){
            //跳转到引导页，设置session标记
            httpSession.setAttribute("isFromAdPage",true);
            return "redirect:"+liveAdPageEntity.getPageUrl();
        }
        return null;
    }

    /**
     * 获取微博用户信息
     * @param access_token
     * @param uid
     * @return
     */
    public Map<String, Object> getWeiBoUserInfo(String access_token, String uid){
        String urlToGetUser = "https://api.weibo.com/2/users/show.json?access_token="+access_token+"&uid="+uid;
        Map<String,Object> model = new HashMap<>();
        try {
            JSONObject userObject = HttpClientUtils.httpGet(urlToGetUser);
            model.put("name",userObject.getString("name"));
            model.put("uid",userObject.getString("idstr"));
            model.put("avatar",userObject.getString("avatar_large"));
        }catch (Exception e){

        }
        return model;
    }
    //获取qq用户信息
    public Map<String, Object> getQQUserInfo(String access_token, String uid) {
        String urlToGetUser = "https://graph.qq.com/user/get_user_info?access_token="+access_token+"&oauth_consumer_key=101431637&openid="+uid;
        Map<String,Object> model = new HashMap<>();
        try {
            JSONObject userObject = HttpClientUtils.httpGet(urlToGetUser);
            model.put("name",userObject.getString("nickname"));
            model.put("uid",uid);
            model.put("avatar",userObject.getString("figureurl_qq_1"));
        }catch (Exception e){

        }
        return model;
    }


    public Map<String ,Object> orgnaziRoomInfo(LiveRoomEntity liveRoomEntity,String uid,String access_token,String user_type){

        //判断直播状态，未开始，前端判断后显示倒计时和聊天室id
        //正在直播返回聊天室id,
        //已经结束返回评论
        Map<String ,Object> liveInfo = new HashMap<>();
        Map<String, Object> userInfo = new HashMap<>();
        //判断用户是否登录
        if (uid != null && access_token != null && user_type !=null){
            //获取用户信息
            if (user_type.equals("weibo")){
                userInfo = getWeiBoUserInfo(access_token,uid);
            }
            if (user_type.equals("qq")){
                userInfo = getQQUserInfo(access_token,uid);
            }
        }
        liveInfo.put("userInfo",userInfo);
        liveInfo.put("liveState",liveRoomEntity.getLiveStatus());
        liveInfo.put("roomId",liveRoomEntity.getLiveRoomId());
        liveInfo.put("title",liveRoomEntity.getEventTitle());
        liveInfo.put("timeStart",liveRoomEntity.getEventStartTime());
        liveInfo.put("roomDesc",liveRoomEntity.getEventDesc());
        liveInfo.put("backImg",liveRoomEntity.getBackImg());
        liveInfo.put("videoPoster",liveRoomEntity.getLivePoster());
        //获取自定义菜单
        List<LiveRoomTabEntity> liveRoomTabEntities = liveRoomTabService.queryByLiveRoomId(liveRoomEntity.getLiveRoomId());
        liveInfo.put("tabs",liveRoomTabEntities);
        if (liveRoomEntity.getLiveStatus() == 2){
            //添加回看人数
            liveRoomService.increaseRepalyVisitedNum(liveRoomEntity.getLiveRoomId());
            //直播结束,关闭聊天室，返回留言，允许留言评论
            //获取回看录制列表
            List<LiveRecordEntity> liveRecordEntities = liveRecordService.queryByLiveRoomId(liveRoomEntity.getLiveRoomId());
            List<String> replayUrls = new ArrayList<>();
            for (LiveRecordEntity liveRecordEntity : liveRecordEntities){
                replayUrls.add(liveRecordEntity.getVideoUrl());
            }
            liveInfo.put("replayUrls",replayUrls);
            liveInfo.put("visitedNumber",liveRoomEntity.getReplayVisitedNum() + liveRoomEntity.getOnlineVisitedNum());
            return liveInfo;

        }else {
            //添加在线观看人数
            liveRoomService.increaseOnlineVisitedNum(liveRoomEntity.getLiveRoomId());
            //直播未结束
            liveInfo.put("chatRoomId",liveRoomEntity.getChatRoomId());
            liveInfo.put("rtmpUrl",liveRoomEntity.getLiveRtmp());
            liveInfo.put("hlsUrl",liveRoomEntity.getLiveHls());
            liveInfo.put("flvUrl",liveRoomEntity.getLiveFlv());
            return liveInfo;
            //return R.ok().put("room_info",liveInfo);

        }
    }
}
